/**
 * 验证配置
 */
angular.module("tms")

    // .config(['$httpProvider', function ($httpProvider) { ////跨域
    //     $httpProvider.defaults.withCredentials = true;
    // }])
    //ajax拦截登录
    .config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('httpInterceptor');
    }])
    .factory('httpInterceptor', ['$q', '$injector', '$rootScope', function ($q, $injector, $rootScope) {
        var $loading = $injector.get('$loading');
        var rootScope = $injector.get('$rootScope');
        var $timeout = $injector.get('$timeout');

        var httpInterceptor = {
            'request': function (request) {
                //request.requestTimestamp = new Date().getTime();

                if (request.method == "POST" || request.url.search("EContractDetail") != -1 || request.url.search("AddAgreementEContract") != -1 || request.url.search("AddEContract") != -1) {
                    $loading.start('appLoading');//post请求开启loading
                }
                let loginData = JSON.parse(window.localStorage.getItem("loginData"));
                if (loginData) {
                    request.headers.Authorization = "Bearer " + loginData.jwtToken;
                    // request.headers.append('Authorization',"Bearer "+ loginData.jwtToken)
                }
                
                // console.log($rootScope.unReadList);

                return request;
            },
            'response': function (response) {
                var $ngBootbox = $injector.get('$ngBootbox');
                var state = $injector.get('$rootScope').$state.current.name;
                // response.config.responseTimestamp = new Date().getTime();
                rootScope.stateBeforLogin = state;

                if (!response.data.success && response.data.errorCode) {
                    //  if (response.data.error.errorCode == "100008" || response.data.error.errorCode == "100007") {
                    //      //没有权限

                    //  } else if (response.data.error.errorCode == "100005" || response.data.error.errorCode == "100003" || response.data.error.errorCode == "100003" || response.data.error.errorCode == "100003") {
                    //      //用户未登录
                    //      rootScope.$state.go("login.in");
                    //      $ngBootbox.hideAll();
                    //      localStorage.clear();
                    //     //  bughd('removeUser')
                    //  }
                    switch (response.data.errorCode) {
                        case "100008":
                        case "100007":
                            rootScope.$state.go("app.noauthority");
                            break;
                        case "100003":
                        case "100004":
                        case "100005":
                        case "100006":
                            rootScope.$state.go("login.in");
                            localStorage.clear();
                            break;
                        default:
                            break;
                    }
                }


                /**
                 * 转换时间
                 */
                function transformTime(time: Date, type: any): void {
                    var t = time;
                    var tf = function (i) { return (i < 10 ? '0' : '') + i };
                    return type.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
                        switch (a) {
                            case 'yyyy':
                                return tf(t.getFullYear());
                            case 'MM':
                                return tf(t.getMonth() + 1);
                            case 'mm':
                                return tf(t.getMinutes());
                            case 'dd':
                                return tf(t.getDate());
                            case 'HH':
                                return tf(t.getHours());
                            case 'ss':
                                return tf(t.getSeconds());
                        }
                    });
                }

                $loading.finish('appLoading');//关闭loading
               
                let loginData = JSON.parse(window.localStorage.getItem("loginData"));
                /**新增空进度 */
                function excelEx(): void {
                    $rootScope.excelExportList.unshift({
                        time: transformTime(new Date(), "MM/dd HH:mm:ss"),
                        skey: '',
                        ckey: '',
                        CnFileName: "文件缓冲中...",
                        IsTrue: true,
                        Path: '',
                        ProgressValue: 0,
                        IsCancel: false,
                        IsFakeInfo: true
                    });
                    window.localStorage.setItem('excelExportList',JSON.stringify($rootScope.excelExportList))
                }
                // 导出报表时，立即显示一个0%的进度条
                if ((response.config.url.indexOf('xport') > -1 || response.config.url.indexOf('xpoet') > -1 || response.config.url.indexOf('workreport')>-1) && response.data.success) {
                    if ($(".excels").attr("class").indexOf("open") == -1) {
                        $(".menuss").dropdown('toggle');
                    }
                    $(".fa-download").parent('button').click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    });
                    // console.log(response);
                    excelEx();
                    $rootScope.EnumChildren++;
                    loginData["ExcelNum"] = $rootScope.EnumChildren;
                    loginData["excelTime"].push(transformTime(new Date(), "MM/dd HH:mm:ss"));
                    window.localStorage.setItem("loginData", JSON.stringify(loginData));
                }
                

                //处理返回数据
                var responseReturn = response;
                if (typeof (response.data) === "object") {

                    if (response.data.success || response.data.success === undefined) {
                        if (response.data) {
                            if (response.config.url.indexOf("tms/menu") > 0) {
                                responseReturn = {
                                    error: response.data.errorMessage,
                                    data: {
                                        data: response.data.data
                                    },
                                    success: response.data.success,
                                }
                            } else if (response.config.url.indexOf("GetBankName") > 0) {
                                responseReturn = {
                                    error: response.data.errorMessage,
                                    data: response.data.data.extData,
                                    success: response.data.success
                                }
                            }else {
                                responseReturn = {
                                    error: response.data.errorMessage,
                                    data: response.data.data,
                                    success: response.data.success
                                }
                    
                            }
                        }
                    } 
                    else if(response.config.url.indexOf('tms/order/AddEvaluate')>-1) {//判定是否是 评价
                        //评价  评价次数超出限制
                            responseReturn = {
                                error: response.data.errorCode,
                                data: response.data.data,
                                success: response.data.success
                            }
                            // if(responseReturn.error=="3016"){//"3016" 
                            //     let carrierId=window.localStorage.getItem('CarrierOrderId');
                            //     let refEvaluat = new Wilddog(window.localStorage.getItem("refEvaluate")+'/'+carrierId);
                            //     // console.log('url',refEvaluat)
                            //     $timeout(function () {
                            //         $ngBootbox.hideAll();               
                            //         refEvaluat.remove();
                            //     }, 300);
                            //     responseReturn = $q.reject(response.data);
                            // }else 
                            if(responseReturn.error){
                                $timeout(function () {
                                    $ngBootbox.hideAll();
                                    $ngBootbox.alert(response.data.errorMessage)
                                }, 300)
                                responseReturn = $q.reject(response.data);
                            } 
                        }else if(response.config.url.indexOf('/tms/carowner')>-1){
                            // 调车推荐 地址转换经纬度错误的提示，不弹出
                            responseReturn=responseReturn = $q.reject(response.data);
                        }
                        else{
                            response.config.url.search("GetBankName") != -1
                                || response.config.url.search("BankInfo") != -1
                                || (response.config.url.search("tms/car/") != -1
                                    && response.config.method == "GET"
                                    && response.data.errorMessage.indexOf("车辆编号不存在") > 0)
                                ? console.log(response.data.errorMessage)
                                : $timeout(function () {
                                    $ngBootbox.hideAll();
                                    $ngBootbox.alert(response.data.errorMessage)
                                }, 500);
                            responseReturn = $q.reject(response.data);
                    }
                }

                function errorHint(data) {
                    var informList = [];
                    data.forEach(function (item, index) {
                        if (item.message == "") {
                            item.members.forEach((itemS) => {
                                informList.push(itemS)
                            });
                        } else {
                            informList.push(item.message)
                        }
                    })
                    return informList.join("。")
                }
                return responseReturn;
            }
        }
        return httpInterceptor;
    }
    ])

    //路由监听事件 
    .run(['$rootScope', '$state', function ($rootScope:ImainRootScope, $state) {
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            //$location.path();//获取路由地址 
            // $location.path('/validation').replace(); 
            // event.preventDefault()可以阻止模板解析 ;
            if($rootScope.tcr_startAddress){
                $rootScope.tcr_startAddress=null;
                $rootScope.tcr_endAddress=null;
                $rootScope.tcr_startCityCode=null;
                $rootScope.tcr_endCityCode=null;
            }
        });
        // stateChangeSuccess 当模板解析完成后触发 
        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            $('.modal').map(function () { $(this).modal('hide'); });
            $('.modal-backdrop').remove();
            $('.modal-open').removeClass('modal-open');

        });

    }])
//jq验证--小数点后4位
jQuery.validator.addMethod("isDecimal", function (value, element) {
    var tel = /^[0-9]+(.[0-9]{1,4})?$/;
    return this.optional(element) || (tel.test(value));
}, "小数点后只能保留4位");


